import Component from "../Component.js";
import Type from "../../experience/db/Type.js";
import { LayerType } from "../../experience/db/Type.js";

const Select = ol.interaction.Select;
const Modify = ol.interaction.Modify;

export default class Selector extends Component {
    constructor() {
        super();

        this.coors = [];
        this.pins = [];
        this.popupId = '';

        // sensor图钉框的颜色
        this.colors = [
            "#FF6347", "#D2B48C", "#6A5ACD", "#2E8B57",
            "#808000", "#00FA9A", "#800000", "#FFD700"
        ];

        // 初始化选择器
        this.select = new Select({
            layers: [
                this.drawer.drawer.modifys,
                this.drawer.drawer.tunnels,
                this.drawer.drawer.sensors,
                this.drawer.drawer.monitors,
                this.drawer.drawer.warnings,
                this.drawer.drawer.warningsv2,
                this.drawer.drawer.tracks,
                this.drawer.drawer.positions,
                this.drawer.drawer.waters,
                this.drawer.drawer.fissures,
                this.drawer.drawer.lwpolylines,
                this.drawer.drawer.hatches,
                this.drawer.drawer.splines,
                this.drawer.drawer.faults,
                this.drawer.drawer.vehicles,
                this.drawer.drawer.persons,
                this.drawer.drawer.slightPoint,
                this.drawer.drawer.m_station,
                this.drawer.drawer.m_staff,
                this.drawer.drawer.k_station,
                this.drawer.drawer.k_node,
                this.drawer.drawer.v_camera
            ]
        });
        this.selector();

        // 接收浏览器大小变化的事件
        // this.emitter.on("resize", () => {
        //     const wh = this.utils.screen();
        //     const width = 480, height = wh.height / 4;
        //     for (let i = 0; i < 8; i++) {
        //         const j = i / 4 + 1, pin = this.pins[i];
        //         pin.x = wh.width - width * j;
        //         pin.y = height * (i % 4);
        //         if (pin.popupId !== "") {
        //             this.$$(`#${pin.id}`).css('left', `${pin.x}px`);
        //             this.$$(`#${pin.id}`).css('top', `${pin.y}px`);
        //         }
        //     }
        // });

        // 发送"打开传感器移动"的事件
        this.$$("#open-sensor-move").on("click", () => {
            this.emitter.emit("open-sensor-move");
        });

        // 发送"关闭传感器移动"的事件
        this.$$("#close-sensor-move").on("click", () => {
            this.emitter.emit("close-sensor-move");
        });

        this.isSersorMove = false;
        this.sensorModify = null;

        this.emitter.on("open-sensor-move", () => {
            this.isSersorMove = true;
        });

        this.emitter.on("close-sensor-move", () => {
            this.isSersorMove = false;
            this.emitter.emit("cancel-selected");
            this.drawer.removeInteraction(this.sensorModify);
        });

        this.emitter.on("root-sensor-move", async () => {
            const id = this.utils.getLocalStorage("rootSensor");
            const feature = this.drawer.source(Type.Sensor).getFeatureById(id);
            const point = feature.getGeometry().getCoordinates();
            this.drawer.map.getView().setCenter(point);
            this.drawer.map.getView().setZoom(12);
            await this.sensor(feature);
        });

        // 在某些情况下需要临时让选择器失效
        this.emitter.on("prevent-slector", () => {
            this.select.getFeatures().clear();
            this.drawer.removeInteraction(this.select);
        });

        // 恢复选择器
        this.emitter.on("restore-slector", () => {
            this.selector();
        });
    }

    selector() {
        const self = this;

        self.$$(".warning-popup").css('left', this.utils.left(460));
        self.popup = this.app.popup.create({ el: '.warning-popup' });

        self.select.on("select", (e) => {
            e.target.getFeatures().getArray().map(async (feature) => {
                if (self.drawer.locked || this.emitter.locked) return;

                // 这里为了增强体验,允许点击Esc键取消选择
                window.onkeydown = function (event) {
                    if (event.defaultPrevented) return;

                    let handled = false;
                    if (event.key === "Escape") {
                        handled = true;
                        self.select.getFeatures().clear();
                        self.emitter.emit("selector-escaped");
                        window.onkeydown = null;
                    }

                    if (handled) event.preventDefault();
                }

                // 判断选中的是否为断层的方向点,以免出错
                const id = feature.getId(), type = feature.get('type');

                // 断层创建选择点
                if (id === 'fault-1' || id === 'fault-2') {
                    this.emitter.emit("fault-select-no", feature);
                }

                // 删除断层
                if (type === Type.Fault) {
                    this.emitter.emit("fault-deleted", id);
                }

                // 传感器
                if (type === Type.Sensor) {
                    this.emitter.emit("sensor-selected", feature);
                }

                // 预警区域
                if (type === Type.Warning) { }

                // 预警区域
                if (type === Type.WarningV2) {
                    this.emitter.emit("water-deleted", id);
                }

                // 轨迹线
                if (type === Type.Track) {
                    this.emitter.emit("track-deleted", id);
                }

                // 定位分站
                if (type === Type.Position) {
                    const edit = this.utils.getLocalStorage("edit");
                    if (edit) {
                        this.emitter.emit("position-edited", feature);
                    } else {
                        this.emitter.emit("position-selected", id);
                    }
                }

                // 车辆
                if (type === Type.Vehicle) {
                    this.emitter.emit("vehicle-selected", id);
                }

                // 人员
                if (type === Type.Person) {
                    this.emitter.emit("person-selected", id);
                }

                // 巷道
                if (type === Type.Tunnel) {
                    const mineCode = feature.get("mineCode");
                    const tunnelCode = feature.get("tunnelCode");
                    const json = { mineCode: mineCode, tunnelCode: tunnelCode, from: "tank", type: "tunnel" };
                    window.parent.postMessage(JSON.stringify(json), '*');
                }

                // 监控
                if (type === Type.Monitor) {
                    this.emitter.emit("monitor-deleted", id);
                }

                // 富水区
                if (type === Type.Water) {
                    this.emitter.emit("water-deleted", id);
                }

                // 裂隙带
                if (type === Type.Fissure) {
                    this.emitter.emit("fissure-deleted", id);
                }

                // 陕西局项目用到的图层 selector
                // 人员分站
                if (type === Type.M_Station) {
                    const editStatus = this.utils.getUrlParamer('edit')
                    if(editStatus == 'true') {
                        this.emitter.emit("device-pos-edit", feature);
                    }
                    else {
                        this.emitter.emit("mstation-detail-open", feature);
                    }

                }
                // 人员
                if (type === Type.M_Staff) {
                    const device_id = feature.get('device_id')
                    this.emitter.emit("mstaff-detail-open", feature);

                }
                // 监控分站
                if (type === Type.K_Station) {
                    const editStatus = this.utils.getUrlParamer('edit')
                    if(editStatus == 'true') {
                        this.emitter.emit("device-pos-edit", feature);
                    }
                    else {
                        this.emitter.emit("kstation-detail-open", feature);
                    }

                }
                // 监控测点
                if (type === Type.K_Node) {
                    const editStatus = this.utils.getUrlParamer('edit')
                    if(editStatus == 'true') {
                        this.emitter.emit("device-pos-edit", feature);
                    }
                    else {
                        this.emitter.emit("knode-detail-open", feature);
                    }


                }
                // 工业视频
                if (type === Type.V_Camera) {
                    const editStatus = this.utils.getUrlParamer('edit')
                    if(editStatus == 'true') {
                        this.emitter.emit("device-pos-edit", feature);
                    }
                    else {
                        this.emitter.emit("vcamera-detail-open", feature);
                    }


                }
            });
        })

        // 添加划过图标时间,使其在地图上由箭头变为小手
        self.drawer.map.on('pointermove', function (evt) {
            const flag = self.drawer.map.hasFeatureAtPixel(evt.pixel);
            self.drawer.map.getTargetElement().style.cursor = flag ? 'pointer' : '';
        });

        this.emitter.on("cancel-selected", () => {
            self.select.getFeatures().clear();
            this.emitter.locked = false;
        });

        self.drawer.addInteraction(self.select);
    }

    template() {
        const upload_popup_div = `
            <div class="popup warning-popup" style="width: 420px; height: 420px;">
                <article>
                    <div class="list inline-labels no-hairlines-md">
                        <ul>
                            <li class="item-content item-input">
                                <div class="item-title item-label">预警时间</div>
                                <div class="item-inner">
                                    <span id="warning-start-time"></span>
                                </div>
                            </li>
                            <li class="item-content item-input">
                                <div class="item-title item-label">预警位置</div>
                                <div class="item-inner">
                                    <span id="warning-position"></span>
                                </div>
                            </li>
                            <li class="item-content item-input">
                                <div class="item-title item-label">预警类型</div>
                                <div class="item-inner">
                                    <span id="warning-type"></span>
                                </div>
                            </li>
                            <li class="item-content item-input">
                                <div class="item-title item-label">预警等级</div>
                                <div class="item-inner">
                                    <span id="warning-level"></span>
                                </div>
                            </li>
                            <li class="item-content item-input">
                                <div class="item-title item-label">预警原因</div>
                                <div class="item-inner">
                                    <span id="warning-reason"></span>
                                </div>
                            </li>
                            <li class="item-content item-input">
                                <div class="item-title item-label">处置意见</div>
                                <div class="item-inner">
                                    <span id="warning-suggest"></span>
                                </div>
                            </li>
                            <li class="item-content item-input">
                                <div class="item-title item-label">解除时间</div>
                                <div class="item-inner">
                                    <span id="warning-end-time"></span>
                                </div>
                            </li>
                        </ul>
                    </div>
                </article>
                <footer style="display: flex; justify-content: space-between; align-items: center; height: 60px;">
                    <div style="display: flex; justify-content: start; align-items: center;">
                        <button class="button button-fill" id="warning-popup-delete">删除预警</button>
                        <button class="button button-fill" id="warning-popup-modify">编辑形状</button>
                    </div>
                    <div style="display: flex; justify-content: start; align-items: center;">
                        <button class="button button-fill popup-close" style="background: #808080;">取消</button>
                    </div>
                </footer>
            </div>
        `;
        this.$$('#app').append(upload_popup_div);

        const selector_div = `
            <div class="popup selector-popup" style="width: 420px; height: 440px;">
                <header>选择器配置</header>
                <article>
                    <div class="list">
                        <ul>
                            <li>
                                <label class="item-radio item-radio-icon-end item-content">
                                    <input type="radio" name="selector-config" value="sensor" checked/>
                                    <i class="icon icon-radio"></i>
                                    <div class="item-inner">
                                        <div class="item-title">测点传感器</div>
                                    </div>
                                </label>
                            </li>
                            <li>
                                <label class="item-radio item-radio-icon-end item-content">
                                    <input type="radio" name="selector-config" value="fault" />
                                    <i class="icon icon-radio"></i>
                                    <div class="item-inner">
                                        <div class="item-title">断层</div>
                                    </div>
                                </label>
                            </li>
                            <li>
                                <label class="item-radio item-radio-icon-end item-content">
                                    <input type="radio" name="selector-config" value="warning-point" />
                                    <i class="icon icon-radio"></i>
                                    <div class="item-inner">
                                        <div class="item-title">预警点</div>
                                    </div>
                                </label>
                            </li>
                            <li>
                                <label class="item-radio item-radio-icon-end item-content">
                                    <input type="radio" name="selector-config" value="warning-area" />
                                    <i class="icon icon-radio"></i>
                                    <div class="item-inner">
                                        <div class="item-title">预警面</div>
                                    </div>
                                </label>
                            </li>
                            <li>
                                <label class="item-radio item-radio-icon-end item-content">
                                    <input type="radio" name="selector-config" value="water" />
                                    <i class="icon icon-radio"></i>
                                    <div class="item-inner">
                                        <div class="item-title">富水区</div>
                                    </div>
                                </label>
                            </li>
                            <li>
                                <label class="item-radio item-radio-icon-end item-content">
                                    <input type="radio" name="selector-config" value="fissure" />
                                    <i class="icon icon-radio"></i>
                                    <div class="item-inner">
                                        <div class="item-title">裂隙带</div>
                                    </div>
                                </label>
                            </li>
                        </ul>
                    </div>
                </article>
                <footer style="display: flex; justify-content: end; align-items: center; height: 60px;">
                    <button class="button button-fill popup-close" style="background: #808080;">取消</button>
                </footer>
            </div>
        `;
        this.$$('#app').append(selector_div);
    }

    control() {
        this.$$(".selector-popup").css('left', this.utils.left(460));
        this.configPopup = this.app.popup.create({ el: '.selector-popup' });

        const self = this;
        self.$$("#selector-configure").on("click", () => {
            const name = self.utils.getLocalStorage("selector-config");
            self.$$(`input[name='selector-config'][value='${name}']`).attr("checked", true);
            self.configPopup.open();
        });

        self.$$("input[name='selector-config'][value='sensor']").on("click", () => {
            self.utils.setLocalStorage("selector-config", "sensor");
        });

        self.$$("input[name='selector-config'][value='fault']").on("click", () => {
            self.utils.setLocalStorage("selector-config", "fault");
        });

        self.$$("input[name='selector-config'][value='warning-point']").on("click", () => {
            self.utils.setLocalStorage("selector-config", "warning-point");
        });

        self.$$("input[name='selector-config'][value='warning-area']").on("click", () => {
            self.utils.setLocalStorage("selector-config", "warning-area");
        });

        self.$$("input[name='selector-config'][value='water']").on("click", () => {
            self.utils.setLocalStorage("selector-config", "water");
        });

        self.$$("input[name='selector-config'][value='fissure']").on("click", () => {
            self.utils.setLocalStorage("selector-config", "fissure");
        });
    }
}